<?php

namespace App\DB;

use App\Model\MovieBuyLog;
use App\Model\MovieVip;
use Illuminate\Support\Facades\DB;

class MovieResourceDB
{
    /**
     *
     * 购买影视资源
     *
     * @param $id
     * @param $memberId
     * @param $price
     * @return bool
     */
    public static function buyResource($id, $memberId, $price)
    {
        # 购买影视资源
        # 事务开始
        DB::beginTransaction();
        # 该用户观影券记录
        $movieVip = MovieVip::where('member_id', $memberId)->first();
        # 减去该资源所需观影券
        $movieVip->coupon -= $price;
        if(!$movieVip->save()) {
            DB::rollBack();
            return false;
        }
        $dataBuyLog = [
            'member_id' => $memberId,
            'movie_resource_id' => $id,
            'coupon' => $price
        ];
        # 添加影视资源购买记录
        $result = MovieBuyLog::insert($dataBuyLog);
        if(!$result) {
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;
    }
}